package cn.dliyy.base.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import cn.dliyy.base.bean.KeyValue;
import cn.dliyy.file.CsvUtil;
import cn.dliyy.warehouse.dao.EntityDao;

@Service
public class KeyValueService {

	@Resource
	private EntityDao entityDao;

	public void save(KeyValue kv) {
		entityDao.save(kv);
	}

	public Object get(KeyValue kv) {
		String hql = "from KeyValue a where a.code='" + kv.getCode() + "' and a.codeType='" + kv.getCodeType() + "'";
		List<Object> list = entityDao.createQuery(hql);
		if (list != null && list.size() == 1) {
			kv = (KeyValue) list.get(0);
		}
		return kv;
	}

	public Object get(String code, String codetype) {
		KeyValue kv = new KeyValue();
		String hql = "from KeyValue a where a.code='" + code + "' and a.codeType='" + codetype + "'";
		List<Object> list = entityDao.createQuery(hql);
		if (list != null && list.size() == 1) {
			kv = (KeyValue) list.get(0);
		}
		return kv;
	}

	public List<Object> getList(String codeType) {
		String hql = "from KeyValue a where a.codeType='" + codeType + "'";
		return entityDao.createQuery(hql);
	}

	public Map<String, String> getMap(String codeType) {
		List<Object> list = getList(codeType);
		Map<String, String> map = new HashMap<String, String>();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				KeyValue kv = (KeyValue) list.get(i);
				map.put(kv.getCode(), kv.getValue());
			}
		}
		return map;
	}

	public void importCountryRegions(String fileName) throws IOException {
		CsvUtil cu = new CsvUtil(fileName);
		KeyValue kv = new KeyValue();
		for (int i = 0; i < cu.getRowNum(); i++) {
			kv.setCodeType(cu.getString(i, 0));
			kv.setCode(cu.getString(i, 1));
			kv.setValue(cu.getString(i, 2));
			entityDao.save(kv);
		}
		cu.CsvClose();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		KeyValueService crs = (KeyValueService) appContext.getBean("keyValueService");
		String fileName = "E:/鼎立/工种代码.csv";
		try {
			crs.importCountryRegions(fileName);
		} catch (IOException e) {
			System.out.println("error: " + fileName);
			e.printStackTrace();
		}
		System.out.println("it's end");
	}

}
